package com.vmladenov.cook.core;

import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public final class DateDeserializer implements JsonDeserializer<Date>
{
	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
	{
		String JSONDateToMilliseconds = "\\/(Date\\((.*?)([+-].*)?\\))\\/";
		Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
		Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
		String result = matcher.replaceAll("$2");
		String timeZone = "GMT" + matcher.replaceAll("$3");
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(Long.parseLong(result));
		calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
		return calendar.getTime();
	}
}